<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\base\controller;

use think\Controller;
use think\Db;
use think\Cache;

class Base extends Controller
{
    //判断登录
//	protected function isLogin() {
//		
//		$user_id = StrDecrypt(cookie('user_id'));
//		if( $user_id ){
//			$this->user = Db::name('user')->alias('u')->join('area a','u.area_id = a.area_id')->where('user_id',$user_id)->find();
//		}
//		$this->assign('user',$this->user);
//	}
	
	//连接共用
	protected function joins() {
		
		$Query = Db::name($this->table)->alias('m')->field($this->field);
		if($this->join || $this->joins) {
			
			$joins = $this->joins ?: [$this->join];
			foreach($joins AS $join) {
				$Query = $Query->join($join[0],$join[1],$join[2]);
			}
		}
		if($this->dbview) {
			$Query->view($this->dbview);
		}
		
		
		return $Query;
	}
	
	public function _empty() {
		return $this->out(request()->action());
	}
	
	protected function out($action = '') {
		
		$action = $action ?: request()->action();
		$this->assign('JSFILE', '../template/'.request()->module().'/'.strtolower(request()->controller()).'/'.$action.'.js');
		$this->assign('action',$action);
		$this->assign('user',$this->user);
		
		return $this->fetch($action);
		
	}
	
	protected function popup($action = '') {
		
		$this->assign('notPopup',0);
		
		return $this->out($action);
		
	}
	
	//添加
	public function add() {
		
		if(request()->isPost()) {
			
			$data = $this->data();
			$id = Db::name($this->table)->insertGetId($data);
			
			//更新缓存
			return $this->res($id?1:0 ,[ 'msg' => '','data'=>$id]);
		}
		//选项 
		$this->options();
		
		return $this->out();
		
	}
	
	public function edit() {
		
		$id = input('param.'.$this->id.'/d');
		
		if(!$id) {
			return $this->error('入口非法，请重试');
		}
		//提交
		if(request()->isPost()) {
			
			$data = $this->data();
			$rslt = Db::name($this->table)->where($this->id,$id)->update($data);
				
			return $this->res($rslt,['修改并保存成功','内容未修改或网络问题，请联系开发者 i@fazi.me'],1);
			
		}
		//连接查询
		$item = $this->joins()->where($this->id,$id)->field($this->field)->find();
		//选项
		$item = $this->options($item);
		$this->assign('item',$item);
		
		return $this->out('add');
		
	}

    //DATA
    protected function data() {
        $P = input('post.');

        //ID
        if( isset($P['id']) ) {
            $P[$this->id] = $P['id'];
            unset($P['id']);
        }
        //数据整理
        $P = array_map('Arr2Set',$P);
        $this->validData( $P );#验证
        $data = $this->parseData( $P );

        //数组值变SET
        if($data[$this->id]) {

        } else {
            unset($data[$this->id]);
        }
        //上传图片
        $data = $this->upload($data);

        return $data;
    }
	
	//删除 
	public function delete() {
		
		$id = input('post.id/a');
		
		if($id) {
			if(is_array($id)) $id = implode(',',$id);
			$rslt = Db::name($this->table)->whereIn($this->id,$id)->setField('delete_time',time());
		}
		
		return $this->res($rslt);
		
	}
    
    /**
	* 自定义响应
	* @param undefined $success
	* @param undefined $url
	* 
	* @return
	*/
	protected function res($success,$msg = '',$url = '',$cache = '') {
		
		if($success){
			$error = 0;
			//清理缓存
			$cache && cache($cache,NULL);
		} else {
			$error = 1;
		}
		
		return $this->msg($url,$error,$msg);
	}
    
    /**
	* 操作结束后提示
	* @param str $url 
	* @param int $error 
	* @param str $msg
	* @param int $sec
	* 
	* @return
	*/
	public function msg($url = '', $error = 0, $msg = '',$sec = 2) {
		
		$data = [];
		//MSG 为数组时可带数据
		if(is_array( $msg )) {
			$data = $msg['data'];
			$msg = $msg['msg'][$error] ?: $msg[$error];
		}
		if(is_numeric($url)){
			$data['url'] = $url;
			$url = '';
		}

		$msg = $msg ? lang($msg) :'';#语言包
		
		if( request()->isAjax() ){
			
			if($error){
				return $this->error($msg,$url,$data,$sec);
			} else {
				return $this->success($msg,$url,$data,$sec);
			}
			
		} else {
			
			//直接跳转
			if($sec == 0) {
				return $this->redirect($url);
			}
			
//			$this->assign('JSFILE', '../application/index/view/common/msg.js');
			$this->assign('url',$url);
			$this->assign('msg',$msg);
			$this->assign('sec',$sec);
			$this->assign('error',$error);
			return $this->fetch('common/msg');
			
		}
	}
	/**
	* 导出excel
	* @param string $filename 文件名
	* @param array $title 列名
	* @param array $data 数据
	* 
	* @return 
	*/
	protected function xls($filename= '',$title=[],$data=[]) {
		
		
		header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        if (!empty($title)) {
            foreach ($title as $k => $v) {
                $title[$k] = iconv("UTF-8", "GB2312", $v);
            }
            $title = implode("\t", $title);
            $content = "$title\n";
        }
        
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $data[$k] = iconv("UTF-8", "GB2312", implode("\t", $v) );
            }
            $content .= implode("\n", $data);
        }
        
        return $content;
	}
	
	protected function apiout($success,$data = [],$msg = '',$url = '') {
		
		/*$origin = isset($_SERVER['SERVER_NAME'])? $_SERVER['SERVER_NAME'] : '';  
  
		$allow_origin = ['www.c.com'];
		
		if(in_array($origin, $allow_origin)){  
		    header('Access-Control-Allow-Origin:*');       
		}*/
		header('Access-Control-Allow-Origin:*'); 
		
		$data = empty($data) ? $success : $data;
		if($success){
			$info = ['code'=>1, 'data' => $data ];
		} else {
			$info = ['code'=>0, 'data' => $msg ];
		}
		
		return json($info);
	}
}
